 //
//  OCLoadViewController.m
//  ocVB
//
//  Created by apple on 2016/10/27.
//  Copyright © 2016年 apple. All rights reserved.
//

#import "OCLoadViewController.h"
#import "OCUserInfoViewModel.h"

@interface OCLoadViewController ()<UIWebViewDelegate>

@property(nonatomic,weak)UIWebView * webV;

@end

@implementation OCLoadViewController

-(void)loadView{
   UIWebView *webV = [[UIWebView alloc] init];
    NSString *uslStr =[ @"https://api.weibo.com/oauth2/authorize?client_id=" stringByAppendingString:OCAPPKEY];
    NSString *Str = [uslStr stringByAppendingString:@"&redirect_uri="];
    NSString *urlS = [Str stringByAppendingString:OCREDIRECTURI];
    NSURL *url = [NSURL URLWithString:urlS];
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    [webV loadRequest:request];
    webV.delegate = self;
    self.webV = webV;
    self.view = webV;
    
    
}
- (void)viewDidLoad {
    [super viewDidLoad];
    [self setNav];
   
}

-(void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
    
}

/**
 取消填写
 */
-(void)cancle{
    [self dismissViewControllerAnimated:YES completion:nil];
}

/**
 自动填充
 */
- (void)antoDo{
    // let jsString = "document.getElementById('userId').value='\(MYWBNAME)',document.getElementById('passwd').value='\(MYWBPASSWD)'"

    
    NSString *jsString = [NSString stringWithFormat:@"document.getElementById('userId').value='%@',document.getElementById('passwd').value='%@'",OCWBNAME,OCWBPASSWD];
    NSLog(@"%@",jsString);
    [self.webV stringByEvaluatingJavaScriptFromString:jsString];
}

-(void)setNav{
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc]initWithCustomView:[UIButton makeButtonWithImgName:nil title:@"取消" titleFont:STANDARDFONT titleColor:ORANGECOLOR tagert:self selector:@selector(cancle)]];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:[UIButton makeButtonWithImgName:nil title:@"自动填充" titleFont:STANDARDFONT titleColor:ORANGECOLOR tagert:self selector:@selector(antoDo)]];
    
}

-(BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType{
    NSString *URLstring = request.URL.absoluteString;
    if ([URLstring hasPrefix:OCREDIRECTURI]) {
         NSString *query = request.URL.query;
        NSLog(@"%@",query);
        NSString *code = [query substringFromIndex:@"code=".length];
        
        [[OCUserInfoViewModel sharedInfoModel] getUserAccount:code finish:^(BOOL isSuccess) {
            if (isSuccess) {
                [SVProgressHUD showSuccessWithStatus:@"登录成功"];
                [[NSNotificationCenter defaultCenter] postNotificationName:MYSWITCHVC object:nil];
            }else{
                [SVProgressHUD showErrorWithStatus:@"登录失败"];
                [self dismissViewControllerAnimated:YES completion:nil];
            }
        }];
        
        return NO;
        
    }
    
    return YES;
}


@end
